'''
输入一个整型数组，数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
示例1:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大，为 6
'''
def maxSubArray(nums):
    # 动态规划，原地修改数组
    maxnum = nums[0]
    for i in range(1, len(nums)):
        if nums[i - 1] > 0:
            nums[i] += nums[i - 1]
        maxnum = max(maxnum, nums[i])
    return maxnum
def func(nums):
    maxnum = None
    tmpnum = 0
    for i in nums:
        if maxnum == None:
            maxnum = i
        if tmpnum + i < i:
            tmpnum = i
        else:
            tmpnum += i
        if maxnum < tmpnum:
            maxnum = tmpnum
    return maxnum
if __name__ == '__main__':
    print(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
    # print(maxSubArray([3,-2,-3,-3,1,3,0]))
    # print(maxSubArray([1,1,-2]))




